package com.snopy.designPattern.chainOfResponsibility.impl;

import com.snopy.designPattern.chainOfResponsibility.inter.Middleware;
import lombok.extern.slf4j.Slf4j;

/**
 * @author snopy
 * @version 1.0.0
 * @classname ThrottlingMiddleware
 * @description
 * @email 77912204@qq.com
 * @date 2022/03/04 13:08
 */
@Slf4j
public class ThrottlingMiddleware extends Middleware {
    private int requestPerMinute;
    private int request;
    private long currenTime;

    public ThrottlingMiddleware(int requestPerMinute) {
        this.requestPerMinute = requestPerMinute;
        this.currenTime = System.currentTimeMillis();
    }

    @Override
    public boolean check(String username, String password) {
        if (System.currentTimeMillis()>currenTime+60_000){
            request = 0;
            currenTime = System.currentTimeMillis();
        }
        request++;
        if (request > requestPerMinute){
            log.info("Request limit exceeted!");
            Thread.currentThread().interrupt();
        }
        return checkNext(username,password);
    }

}
